#!/bin/env python
# -*- coding: utf-8 -*-

import urllib.request
import urllib.parse
import json



#DNSPOD
class Dnspod:

    _base_url = "https://dnsapi.cn/%s"

    #构造方法
    def __init__(self, username, password, lang="cn"):
        self._username = username
        self._password = password
        self._lang = lang

    #POST请求数据
    def _post(self, uri, param):
        param["login_email"] = self._username;
        param["login_password"] = self._password;
        param["lang"] = self._lang;
        param["error_on_empty"] = "yes";
        param["format"] = "json";
        param_string = urllib.parse.urlencode(param);

        user_agent = "CHENGXUAN DDNS_PYTHON Client/1.0.0 (lcx165@gmail.com)"
        url = self._base_url % (uri)

        req = urllib.request.Request(url)
        req.add_header("User-agent", user_agent)
        req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")

        r = urllib.request.urlopen(req, param_string.encode("UTF-8"))

        ret = r.read().decode('utf-8')
        ret = json.loads(ret)

        if(int(ret["status"]["code"]) < 0) :
            raise DnspodRetException(ret["status"]["code"], ret["status"]["message"], uri)

        return ret

    # ##################### 以下为具体公开方法 ##################### #

    #获取域名信息
    def domain_info(self, domain):
        return self._post("Domain.Info", {"domain":domain})

    #修改DNS记录
    def record_modify(self):
        return self._post("Record.Modify", {})

    #动态更新记录IP
    def record_ddns(self, domain_id, record_id, sub_domain, record_line):
        return self._post("Record.Ddns", {
            "domain_id"   : domain_id,
            "record_id"   : record_id,
            "sub_domain"  : sub_domain,
            "record_line" : record_line,
        })

    #监控列表
    def monitor_listsubvalue(self, domain, subdomain):
        return self._post("Monitor.Listsubvalue", {
            "domain"    : domain,
            "subdomain" : subdomain,
        })





#结果异常
class DnspodRetException(Exception) :

    def __init__(self, error_code, error, request):
        self.error_code = error_code
        self.error = error
        self.request = request
        Exception.__init__(self, error)

    def __str__(self):
        return u"DNSPOD错误: %s(%s); %s" % (self.error, self.error_code, self.request)